#include "softwarescan.h"
#include "enetwork.h"
#include <QCoreApplication>
#include "mylogger.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include "machineutil.h"

using namespace ns_yht;

SoftwareScan::SoftwareScan(const QString &code)
{
    m_model.reset(new ModelSoftware);
    m_model->code = code;
}

SoftwareScan::SoftwareScan(const QString &code, const QString &currentVersion)
{
    m_model.reset(new ModelSoftware);
    m_model->code = code;
    m_model->currentVersion.setVersion(currentVersion);
}

SoftwareScan::~SoftwareScan()
{
}

void SoftwareScan::start()
{
    MachineUtil mutil;
    QString url = QString("http://restapi.ehanghai.cn/xxyc-api/softwareVersion/%1").arg(m_model->code);
    if (GLOG)
        GLOG->info("SoftwareScan::start......");
    QNetworkReply *reply = ENetwork::Get(url, "", "", true);
    connect(reply, &QNetworkReply::finished, this, [=]
            { onProcessFinished(reply); });
}

void SoftwareScan::onProcessFinished(QNetworkReply *reply)
{
    if (ENetwork::checkReplyError(reply))
    {
        m_model->state = VersionScanResult::Error;
        if (GLOG)
            GLOG->info("SoftwareScan ReplyError!");
        emit finished();
        return;
    }
    const QJsonDocument &jsonDocument = QJsonDocument::fromJson(reply->readAll());
    reply->deleteLater();

    if (!jsonDocument.isNull())
    {
        const QJsonObject &rootObj = jsonDocument.object();
        if (rootObj.value("success").toBool())
        {
            auto item = rootObj.value("data").toObject();
            setModel(item);
        }
        else
        {
            m_model->state = VersionScanResult::Error;
            m_model->versionDescription = rootObj.value("errorMsg").toString();
            if (GLOG)
                GLOG->info(QString("SoftwareScan ReplyError! - %1").arg(m_model->versionDescription).toStdString());
        }
    }

    if (GLOG)
        GLOG->info("SoftwareScan Finished. code:{}   result: {}", m_model->code.toStdString(), int(m_model->state));

    emit finished();
}

void SoftwareScan::setModel(const QJsonObject &appObj)
{
    QSharedPointer<ModelSoftware> model = m_model;

    model->name = appObj.value("name").toString();
    model->remoteVersion.setVersion(appObj.value("version").toString());
    model->versionDate = appObj.value("versionDate").toString();
    model->versionDescription = appObj.value("description").toString();
    model->fileName = appObj.value("fileName").toString();
    if (appObj.contains("downloadUrl"))
        model->url = appObj.value("downloadUrl").toString();
    if (model->currentVersion < model->remoteVersion)
        model->state = VersionScanResult::NeedUpdate;
    else
    {
        model->state = VersionScanResult::NoNeedUpdate;
        model->updated = true;
    }
}

QSharedPointer<ModelSoftware> SoftwareScan::getModel() const
{
    return m_model;
}
